#include "datafile.h"

//**********************DataFile*********************
DataFile::DataFile(QObject *parent) : QObject(parent)
{
    HeaderSize = 326; // 所有数据实际字节数综合，没有字节对齐
}

void DataFile::InitHeaderInfo(int Ver, int AdBit, int DataLen, double Freq,
                              int ChNum, int SampCh, QString PointNum, float Sensitivity,
                              int Multiple, QString Unit, QString Remark)
{
    DataHeader.bfSize = 326 + DataLen;
    DataHeader.diVer = Ver;
    DataHeader.diADBit = AdBit;
    DataHeader.diSize = DataLen;
    DataHeader.diSampleFreq = Freq;
    DataHeader.diChannelNum = ChNum;
    DataHeader.diCh = SampCh;
    strncpy(DataHeader.diTestPointNum, PointNum.toStdString().c_str(), 10);
    DataHeader.diSensitivity = Sensitivity;
    DataHeader.diMultiple = Multiple;
    strncpy(DataHeader.diUnit, Unit.toStdString().c_str(), 20);
    strncpy(DataHeader.diRemark, Remark.toStdString().c_str(), 256);
    strncpy(DataHeader.bfType, "VIPC", 4);
    DataHeader.bfType[4] = '\0';
    strncpy(DataHeader.diDataFlag, "data", 4);
}

bool DataFile::WriteChData(QString FileName, float *SampChData, int DataLen)
{
    QFile file(FileName);
    if(!file.open(QIODevice::WriteOnly)) {
        // 打开文件失败，提示后返回
        return false;
    }
    file.seek(0);
    file.write((char*)DataHeader.bfType, 4);
    file.write((char*)&DataHeader.bfSize, sizeof(int));
    file.write((char*)&DataHeader.diVer, sizeof(short));
    file.write((char*)&DataHeader.diADBit, sizeof(short));
    file.write((char*)&DataHeader.diSize, sizeof(int));
    file.write((char*)&DataHeader.diSampleFreq, sizeof(double));
    file.write((char*)&DataHeader.diChannelNum, sizeof(short));
    file.write((char*)&DataHeader.diCh, sizeof(short));
    file.write((char*)DataHeader.diTestPointNum, 10);
    file.write((char*)&DataHeader.diSensitivity, sizeof(float));
    file.write((char*)&DataHeader.diMultiple, sizeof(int));
    file.write((char*)DataHeader.diUnit, 20);
    file.write((char*)DataHeader.diRemark, 256);
    file.write((char*)DataHeader.diDataFlag, 4);
    file.write((char*)SampChData, DataLen * sizeof(float));
    file.close();

    return true;
}
